package rsvp.util;

import java.io.File;
import java.net.URI;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Determine log path if in class or in library, or ... (not finished yet)
 * At the moment working only if it's as class and class directory is named bin.
 * 
 * @author Kuki Szabolcs @version 2005-01-12
 */
public class PathToApplicationRoot {
    
	private static File fWorkingDirectory = null;
    public static final String sTimeStampForApplicationStart = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());

	/**
	 * @return the root directory
	 * @author Kuki Szabolcs @version 2005-01-12
	 */
	public static File getApplicationRootDirectory() {
	    if (fWorkingDirectory != null)
	        return fWorkingDirectory;
	    
		URL url = PathToApplicationRoot.class.getResource("");
//		System.out.println("MyAppPaths.getWorkDirAsString() url = " + url);
		String sBuildDir = "./";
		
	 
		if (null != url) {
            String sToString = url.toString();
            int posExlamation = sToString.indexOf("!");
            if (posExlamation > 0) {                
				int posDir = sToString.lastIndexOf("/", posExlamation);                
                sBuildDir = sToString.substring(0, posDir);
                final String jarPrefix = "jar:";
				if (sBuildDir.startsWith(jarPrefix))
                	sBuildDir = sBuildDir.substring(jarPrefix.length());
            }
            else {               
				int posBinDir = sToString.lastIndexOf("/bin/");                
				//int posDir = sToString.lastIndexOf("/", posClasses - 1);                
                sBuildDir = sToString.substring(0, posBinDir);
            }
        }
//		System.out.println("MyAppPaths.getWorkDirAsString() sBuildDir = " + sBuildDir);
		
		File fWorkDirectory = null;
		
		try {
			URI uri = new URI(sBuildDir);
			fWorkDirectory = new File(uri);
		} catch (Exception e) {
			e.printStackTrace();
		}
				 
		return fWorkDirectory;
	}
}
